package com.sam.spring.security.compent;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sam.spring.security.enums.LoginTypeEnum;
import com.sam.spring.security.properties.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @classname: AuthSuccessHandler
 * @description: 自定义登陆成功处理类
 * @Author: sam
 * @date: 2021/6/29 17:26
 */
@Slf4j
@Component
public class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        log.info("CustomAuthenticationSuccessHandler login success!");
        if (LoginTypeEnum.JSON.equals(securityProperties.getLoginType())){
            response.setContentType("application/json;charset=UTF-8");
            // 把authentication对象转成 json 格式 字符串 通过 response 以application/json;charset=UTF-8 格式写到响应里面去
            response.getWriter().write(objectMapper.writeValueAsString(authentication));
        }else {
            // 父类的方法 就是 跳转
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }
}
